package offer;

/**
 * 剑指 Offer 04. 二维数组中的查找
 */
public class FindNumberIn2DArray {
    public static void main(String[] args) {
        int[][] matrix = {
                {1, 4, 7, 11, 15},
                {2, 5, 8, 12, 19},
                {3, 6, 9, 16, 22},
                {10, 13, 14, 17, 24},
                {18, 21, 23, 26, 30}
        };

        boolean b = findNumberIn2DArray(matrix, 5);
        System.out.println(b);
    }

    public static boolean findNumberIn2DArray(int[][] matrix, int target) {
        int i = matrix[0].length - 1;
        int j = 0;
        while (j < matrix.length && i >= 0) {
            if (target > matrix[j][i]) {
                i++;
            } else if (target < matrix[i][j]) {
                j--;
            } else {
                return true;
            }
        }
        return false;
    }
}
